package auth

import (
	"beegoProject08/models/auth"
	"beegoProject08/utils"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"math"
)

type AuthController struct {
	beego.Controller
}

func (c *AuthController) List() {

	// 1 初始化数据库
	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth")

	// 2 每夜显示到条数 -> pagePerNum
	pagePerNum := 5

	// 3 当前页 -> currentPage
	currentPage, err := c.GetInt("page")
	if err != nil {
		currentPage = 1
	}

	// 4 数据总量 -> count
	count, _ := qs.Filter("is_delete", 0).Count()

	// 5 总页数 -> countPage
	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))

	pageMap := utils.Paginator(currentPage, pagePerNum, count)

	// 7 数据查询
	auths := []auth.Auth{}
	qs.Filter("is_delete", 0).All(&auths)
	c.Data["auths"] = auths

	// 8 (下一页)当前页数小于总页数，下一页可以+1
	nextPage := 1
	if currentPage < countPage {
		nextPage = currentPage + 1
	} else if currentPage >= countPage { // 最后页就不能+1
		nextPage = currentPage
	}

	// (上一页)当前页面=1，不能-1
	prePage := 1
	if currentPage == 1 {
		prePage = currentPage
	} else if currentPage > 1 {
		prePage = currentPage - 1
	}

	// 6 传入前端
	c.Data["pageMap"] = pageMap
	c.Data["countPage"] = countPage
	c.Data["count"] = count

	// 9 前端分页
	c.Data["currentPage"] = currentPage
	c.Data["nextPage"] = nextPage
	c.Data["prePage"] = prePage

	c.TplName = "auth/auth-list.html"
}
